/*
 * Copyright (c) 2017 Qunar.com. All Rights Reserved.
 */
package com.guoyu.project.common.ueditor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Maps;
import com.guoyu.project.common.spring.ApplicationContextSupport;
import com.guoyu.project.common.ueditor.model.UeditorResult;
import com.guoyu.project.common.ueditor.service.UeditorHandler;
import com.guoyu.project.common.utils.JsonUtil;
import com.guoyu.project.common.utils.PropertyUtil;
import com.guoyu.project.service.FileUploadService;

/**
 * 百度Ueditor上传controller
 *
 * @author: libo Date: 17-6-19 Time: 上午11:49
 * @version: \$Id$
 */
@Controller
@RequestMapping("baidu/ueditor")
public class UeditorController implements InitializingBean {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private ApplicationContextSupport applicationContextSupport;

    @Resource
    private FileUploadService fileUploadService;

    private String domain = PropertyUtil.getProperty("domain");

    private Map<String, UeditorHandler> handlerMapper = Maps.newHashMap();

    @RequestMapping("upload")
    public void upload(
            @RequestParam(value = UeditorDefaultConfig.FILE_FIELD_NAME, required = false) MultipartFile uploadFile,
            HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Content-Type", "text/html");

        PrintWriter printWriter = response.getWriter();

        String actionType = request.getParameter("action");
        if (StringUtils.equals(actionType, "config")) {
            printWriter.write(JsonUtil.encode(UeditorDefaultConfig.defaultConfigMap));
            return;
        }

        UeditorHandler ueditorHandler = handlerMapper.get(actionType);
        UeditorResult ueditorResult;
        if (ueditorHandler == null) {
            ueditorResult = UeditorResult.fail("后台未实现的action");
        } else {
            ueditorResult = ueditorHandler.handle(request, uploadFile);
        }
        printWriter.write(JsonUtil.encode(ueditorResult));
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        List<UeditorHandler> handlerList = applicationContextSupport.getBeans(UeditorHandler.class);
        for (UeditorHandler ueditorHandler : handlerList) {
            handlerMapper.put(ueditorHandler.getActionType().name(), ueditorHandler);
        }
    }
}
